package user

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"ttsx/server/common/global"
	"ttsx/server/model"
	"ttsx/server/utils"
)

func Active(ctx *gin.Context) {
	token := ctx.Query("token")

	// 解析token
	cliam, err := utils.ParseToken(token, global.App.Config.Jwt.AccessSecret)
	if err != nil {
		global.App.Log.Error(err.Error())
		ctx.Redirect(http.StatusFound, "/ttsx/index")
	}

	var activeUser model.User
	if ret := global.App.DB.Where("name = ?", cliam.Name).Where("email = ?", cliam.Email).Find(&activeUser); ret.RowsAffected == 0 {
		global.App.Log.Error("激活用户不存在")
		ctx.Redirect(http.StatusFound, "/ttsx/index")
	}

	if cliam.ExpiresAt.Before(time.Now()) {
		global.App.Log.Error("激活链接已过期,请重新注册")
		global.App.DB.Where("id = ?", activeUser.ID).Unscoped().Delete(&model.User{})
		ctx.Redirect(http.StatusFound, "/ttsx/user/register")
	}

	// 更新isActive 字段
	if ret := global.App.DB.Where("id = ?", activeUser.ID).Updates(&model.User{IsActive: true}); ret.RowsAffected == 0 {
		global.App.Log.Error("激活用户失败")
		ctx.Redirect(http.StatusFound, "/ttsx/index")
	}

	global.App.Log.Sugar().Infof("%s: 账号已激活", activeUser.Name)
	ctx.Redirect(http.StatusFound, "/ttsx/user/login")
}
